# coding=utf-8
import bytedance.context
from euler import base_compat_middleware
from euler.client import Client

from apitest.engine.env import run_env
from apitest.engine.logging import logger


class RPCError(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message
        super(RPCError, self).__init__('code: %s, message: %s' % (code, message))


def check_base_resp_middleware(ctx, *args, **kwargs):
    resp = ctx.next(*args, **kwargs)
    if resp.BaseResp and resp.BaseResp.StatusCode != 0:
        raise RPCError(resp.BaseResp.StatusCode, resp.BaseResp.StatusMessage)
    return resp


def logging_middleware(ctx, req):
    """
    增加日志
    :type ctx: Context
    :param req
    """
    # logger.info(ctx.url)  # 协议，psm信息 基本信息
    # logger.info(ctx.local)
    logger.info("logid is: %s, runtime env is: %s" % (ctx.persistent.get("logid"), ctx.persistent.get("env")))
    logger.info("[%s] request: %s" % (ctx.name, req))
    result = ctx.next(req)
    logger.info("[%s] response data: %s" % (ctx.name, result))
    return result


class BaseRPCClient(Client):

    def __init__(self, service_cls, psm, cluster="default", **kwargs):
        bytedance.context.set("env", run_env.env_tag)  # 设置环境
        self.target = "sd://{}?cluster={}".format(psm, cluster)
        super(BaseRPCClient, self).__init__(service_cls, self.target, **kwargs)
        self.use(base_compat_middleware.client_middleware)
        # self.use(check_base_resp_middleware)
        self.use(logging_middleware)
